extends Node
signal playSound(soundName)

onready var _player=$AudioStreamPlayer
var soundArr:Array=[]
var soundDic={}
var _lastSoundId=-1
var lastSoundName=''
var _soundIndex=0
func _ready():
	randomize()
	soundArr=($SoundLab.soundArr as Array).duplicate()
	for data in soundArr:
		soundDic[data.id]=data
	_player.connect("finished",self,'_onSoundFinish')
	_resetArr()
	_play()
func _resetArr(): 
	print('resetArr')
	if soundArr.size()==0:
		return
	soundArr.shuffle()
	_soundIndex=0
	#保证随机后的第一首歌不和前一首播放的歌一样
	if soundArr[0].id==_lastSoundId: 
		var d=soundArr.pop_front()
		soundArr.push_back(d)
func _play():
	if _soundIndex>=soundArr.size():
		return
	var data=soundArr[_soundIndex]
	var id=data.id
	_lastSoundId=id
	lastSoundName=data.name
	var stream=load('res://sounds/'+str(id)+'.mp3')
	_player.stream=stream
	_player.play(0)
	emit_signal("playSound",lastSoundName)
func nextSound():
	_soundIndex+=1
	if _soundIndex>=soundArr.size():
		_resetArr()
	_play()

func _onSoundFinish():
	nextSound()

func _process(delta):
	
	pass
